package com.jiexin.util;

import com.jiexin.common.ConfigDatasource;
import com.jiexin.model.Mail;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Slf4j
@Component
public class SMTPMailUtil {


    public static boolean send(Mail mail, ConfigDatasource configDatasource) {

        String from = configDatasource.getConfig("mailAccount");
        int port = Integer.valueOf(configDatasource.getConfig("port"));
        String host = configDatasource.getConfig("mailHost");
        String pass = configDatasource.getConfig("mailPassword");
        String nickname = configDatasource.getConfig("nickName");

        HtmlEmail email = new HtmlEmail();
        try {
            email.setHostName(host);
            email.setCharset("UTF-8");
            for (String str : mail.getReceivers()) {
                email.addTo(str);
            }
            email.setFrom(from, nickname);
            email.setSmtpPort(port);
            email.setAuthentication(from, pass);
            email.setSubject(mail.getSubject());
            email.setMsg(mail.getMessage());
            email.send();
            log.info("{} 发送邮件到 {}", from, StringUtils.join(mail.getReceivers(), ","));
            return true;
        } catch (EmailException e) {
            log.error(from + "发送邮件到" + StringUtils.join(mail.getReceivers(), ",") + "失败", e);
            return false;
        }
    }


}

